<template>
  <div class="tags">
    <el-tag @click="$router.push(item.path)"
            closable
            @close="delTag(index,item)"
            :type=" item.path === $route.path ? 'danger':'primary' "
            v-for="(item,index) in list"
            :key="index">{{item.title}}</el-tag>
  </div>
</template>

<script>
import { setStorage, getStorage } from '@/utils'
export default {
  name: 'TagsView',
  data () {
    return {
      list: getStorage('tagsList') || []
    }
  },
  watch: {
    $route: {
      deep: true,
      immediate: true,
      handler (newval) {
        // 判断存在
        const isExist = this.list.some(val => val.path === newval.path)
        if (isExist) return
        // 不存就插入
        this.list.push({
          title: newval.meta.title,
          path: newval.path
        })
        // 存入本地
        setStorage('tagsList', this.list)
      }
    }
  },
  methods: {
    // 删除标签
    delTag (idx, val) {
      // 判断删除的是否为当前页标签
      if (val.path === this.$route.path) { // 激活项
        if (idx === 0) { // 激活项且是第1个
          this.list.splice(idx, 1)
          this.$router.push('/')
        } else { // 激活项不是第1个
          // 取出左边的
          const url = this.list[idx - 1].path
          this.list.splice(idx, 1)
          this.$router.push(url)
        }
      } else {
        this.list.splice(idx, 1)
      }
      // 存入本地
      setStorage('tagsList', this.list)
    }
  }
}
</script>

<style scoped lang="less">
.tags{
  height: 40px;
  padding: 0 15px;
  background-color: #fafafa;
  border-bottom: 1px solid blue;
  position: absolute;
  left: 0;
  top: 0;
  width: 100%;
  display: flex;
  align-items: center;
  .el-tag{
    margin-right: 10px;
    cursor: pointer;
  }
}

</style>
